﻿using System;
using System.Configuration;
using System.Web.Configuration;
using System.Xml;

namespace FBGraph.Web.Configuration
{
    /// <summary>Defines configuration settings that are used to support WebForms authorization based on the Graph API.</summary>
    public class FBGraphAuthorizationSection : ConfigurationSection
    {
        /// <summary>Overrides the base implementation of <see cref="ConfigurationSection.DeserializeSection" /> to perform additional validation on the configuration.</summary>
        /// <param name="reader">The <see cref="XmlReader" /> which reads from the configuration.</param>        
        protected override void DeserializeSection(XmlReader reader)
        {
            base.DeserializeSection(reader);

            if (
                (this.AppAuthorization == null || !this.AppAuthorization.IsRequired) &&
                (this.ExtendedPermissionsCollection != null && this.ExtendedPermissionsCollection.Count > 0))
            {
                throw new ConfigurationErrorsException("The appAuthorization attribute isRequired must be true if any extended permissions are set.", reader);
            }
        }

        /// <summary>Gets the <c>appAuthorization</c> configuration.</summary>
        [ConfigurationProperty("appAuthorization")]
        public FBGraphAppAuthorizationElement AppAuthorization
        {
            get { return (FBGraphAppAuthorizationElement)this["appAuthorization"]; }
            set { this["appAuthorization"] = value; }
        }

        /// <summary>Gets the <c>extendedPermissions</c> configuration.</summary>
        [ConfigurationProperty("extendedPermissions")]
        [ConfigurationCollection(typeof(FBGraphExtendedPermissionElement))]
        protected FBGraphExtendedPermissionElementCollection ExtendedPermissionsCollection
        {
            get { return (FBGraphExtendedPermissionElementCollection)this["extendedPermissions"]; }
            set { this["extendedPermissions"] = value; }
        }

        /// <summary>Compiles a <see cref="ExtendedPermission" /> value from the list of permissions specified at the current and all parent levels of the configuration.</summary>
        /// <returns>A <see cref="ExtendedPermission" /> representing a mapping of permissions required to execute the current request.</returns>
        public ExtendedPermission GetExtendedPermissions()
        {
            var result = default(ExtendedPermission);
            if (this.ExtendedPermissionsCollection != null)
            {
                foreach (var ep in this.ExtendedPermissionsCollection)
                {
                    result |= ep.Permission;
                }
            }
            return result;
        }
    }
}